package com.arina.onepagesmarthome;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import android.widget.ToggleButton;



/**
 * @author Vien Son
 *San Vuon 
 *2 bo relay : 110 va 250
 *DDNS : shsvilla.dyndns.org
 */
public class SanVuon_activity extends Activity {

	Handler handler;
	NetworkChangeReceiver networkstatus=new NetworkChangeReceiver();
	final int delay = 1000;//thoi gian cho truoc khi thuc hien lenh dau tien
	final int period = 2000;//thoi gian lap lai
	private String[] MySSID ;

	Relay[] arrRelay;
	Runnable r;
	MasterBoard master;

	//khai bao cac bo relay cho activity
	Relay relay110;
	Relay relay250;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.sanvuon);
		
		MySSID=((globaldata) this.getApplication()).ssid;
		master=((globaldata) this.getApplication()).masterboard.get(0);
		registerReceiver(networkstatus, new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE"));
		relay110=new Relay(master, 20, 110, 12);
		relay250=new Relay(master,20,250,6);
		arrRelay=new Relay[]{relay110,relay250};

		//gan button cho relay 110
		arrRelay[0].ArrButton[1]=(ToggleButton)findViewById(R.id.channel4);
		arrRelay[0].ArrButton[3]=(ToggleButton)findViewById(R.id.channel6);
		arrRelay[0].ArrButton[4]=(ToggleButton)findViewById(R.id.sw1);
		arrRelay[0].ArrButton[10]=(ToggleButton)findViewById(R.id.sw2);
		arrRelay[0].ArrButton[11]=(ToggleButton)findViewById(R.id.sw3);
		arrRelay[0].setOnClickListener( COMMAND_TYPE.REVERSE, 0);
		//gan button cho relay 250
		arrRelay[1].ArrButton[0]=(ToggleButton)findViewById(R.id.channel2);
		arrRelay[1].ArrButton[1]=(ToggleButton)findViewById(R.id.channel8);
		arrRelay[1].ArrButton[2]=(ToggleButton)findViewById(R.id.channel1);
		arrRelay[1].ArrButton[3]=(ToggleButton)findViewById(R.id.channel7);
		arrRelay[1].ArrButton[4]=(ToggleButton)findViewById(R.id.channel3);
		arrRelay[1].ArrButton[5]=(ToggleButton)findViewById(R.id.channel5);
		arrRelay[1].setOnClickListener( COMMAND_TYPE.REVERSE, 0);

		
		handler=new Handler();
		for(int i=0;i<arrRelay.length;i++)
		{
			final int index=i;
			r = new Runnable() {
				public void run() {
					//Toast.makeText(getApplicationContext(),"update status",Toast.LENGTH_SHORT).show();
					updateStatus(handler,arrRelay[index]);
					handler.postDelayed(this, period*(index+1));
				}
			};
			handler.postDelayed(r, delay);
		}


		if (savedInstanceState != null) {
			return;
		}
	}

	//	private void updateStatus(final Handler mHandler) {
	//		Thread th=new Thread(){
	//			public void run(){
	//				for(int i=0;i<arrRelay.length;i++)
	//				{
	//					arrRelay[i].readStatusHTTP();
	//				}
	//
	//				mHandler.post(new Runnable() {
	//
	//					@Override
	//					public void run() {
	//						for(int positionRelay=0;positionRelay<arrRelay.length;positionRelay++)
	//						{
	//							if(arrRelay[positionRelay].Response!=null)
	//								updateUI(arrRelay[positionRelay].Response,positionRelay);
	//
	//						}
	//
	//					}
	//				});
	//			};
	//		};
	//		th.start();
	//	}

	private void updateStatus(final Handler mHandler,final Relay relay) {
		Thread th=new Thread(){
			public void run(){
				relay.readStatusHTTP();

				mHandler.post(new Runnable() {

					@Override
					public void run() {

						if(relay.Status!=null)
							updateUI(relay);


					}
				});
			};
		};
		th.start();
	}
	//	private void updateUI(boolean[] arrStatus,int positionRelay) {
	//
	//		for(int i=0;i<arrRelay[positionRelay].ArrButton.length;i++)
	//		{
	//			if(arrRelay[positionRelay].ArrButton[i]!=null)
	//				arrRelay[positionRelay].ArrButton[i].setChecked(!arrStatus[i]);
	//		}
	//
	//
	//	}

	private void updateUI(Relay relay) {

		for(int i=0;i<relay.ArrButton.length;i++)
		{
			if(relay.ArrButton[i]!=null)
				relay.ArrButton[i].setChecked(!relay.Status[i]);
		}


	}


	private class NetworkChangeReceiver extends BroadcastReceiver{
		private NETWORK_STATUS currNetworkStatus;

		//private static final String MyMAC = "48:f8:b3:32:71:80";

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			getNetworkState(context);
		}

		public void getNetworkState(Context context) {

			if(Connectivity.isConnected(context))
			{
				if(Connectivity.isConnectedMobile(context))//mobile
				{
					currNetworkStatus=NETWORK_STATUS.MOBILE;
				}
				else if(Connectivity.isConnectedWifi(context))//wifi
				{
					WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
					WifiInfo wifiInfo = wifiManager.getConnectionInfo();
					String currSSID=wifiInfo.getSSID().trim();
					if (currSSID.startsWith("\"") && currSSID.endsWith("\"")){
						currSSID = currSSID.substring(1, currSSID.length()-1);
					}
					for(int i=0;i<MySSID.length;i++)
					{
						if(!currSSID.equalsIgnoreCase(MySSID[i]))
						{
							//ket noi wifi noi bo
							currNetworkStatus=NETWORK_STATUS.EXTERNAL;
							break;
						}
						currNetworkStatus=NETWORK_STATUS.LOCAL;
					}
				}
			}
			else
			{
				currNetworkStatus=NETWORK_STATUS.NOT_CONNECTED;
			}
			master.setCurrentAddress(currNetworkStatus);
			Toast.makeText(getApplicationContext(), currNetworkStatus.toString(), Toast.LENGTH_SHORT).show();
		}

	}


	public char[] getMacId() {

		WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
		WifiInfo wifiInfo = wifiManager.getConnectionInfo();
		return wifiInfo.getBSSID().toCharArray();
	}
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		getMenuInflater().inflate(R.menu.one_page_smarthome, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}


	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		handler.removeCallbacks(r);
		unregisterReceiver(networkstatus);
	}

	@Override
	protected void onResume() {
		super.onResume();
		handler.post(r);
		registerReceiver(networkstatus, new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE"));

	}


}
